package tech.aistar.day01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 本类用来演示: 创建cookie,获取cookie
 *
 * @author: success
 * @date: 2021/4/15 3:38 下午
 */
@WebServlet(urlPatterns = "/cookie/*")
public class CookieCreateController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();//获取 /*

        switch (pathInfo){
            case "/set":
                //1. 在server端创建一个cookie对象
                // 细节的地方 - cookie的value是不允许出现中文的.

                //中文数据需要进行存储 - 编码操作
                //一级编码/二级编码
                String uname = "平平";
                //uname = URLEncoder.encode(uname,"utf-8");//一级编码
                //uname = URLEncoder.encode(uname,"utf-8");//二级编码

                uname = URLEncoder.encode(URLEncoder.encode(uname,"utf-8"),"utf-8");

                Cookie c = new Cookie("loginInfo",uname+":123");
                //2. 设置一些可选的属性
                c.setPath("/");//设置作用域
                c.setMaxAge(60);//过期时间,单位是s秒

                //3. 调用HttpServletResponse#addCookie方法,通过响应头信息将这个cookie发送到client端
                //并且保存在客户端
                resp.addCookie(c);

                break;
            case "/get":
                //只要server发送了cookie给客户端
                //那么客户端在下次建立请求的时候,就会带上这个cookie - 请求头信息
                //1. 获取所有的cookie
                Cookie[] cookies = req.getCookies();
                //判断一下
                if(null!=cookies && cookies.length>0){
                    for (Cookie cookie : cookies) {
                        if("loginInfo".equals(cookie.getName())){
                            //获取value
                            String value = cookie.getValue();
                            String[] arr = value.split(":");
                            //二级解码
                            String result = URLDecoder.decode(URLDecoder.decode(arr[0],"utf-8"),"utf-8");
                            System.out.println("用户名:"+result);
                            System.out.println("密码:"+arr[1]);
                        }
                    }
                }
                break;
        }
    }
}
